import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import router from '@/router'
import { getStamp } from '@/utils/auth'
const defaultStamp = 3600
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000
})

service.interceptors.request.use(config => {
  if (store.getters.token) {
    if (CheckTimeStamp()) {
      store.dispatch('user/logout')
      router.push('/login')
      return Promise.reject(new Error('token超时了'))
    }
    config.headers.Authorization = `Bearer ${store.getters.token}`
  }
  // 在发送请求之前做些什么
  return config
}, error => {
  // 对请求错误做些什么
  return Promise.reject(error)
})

service.interceptors.response.use(response => {
  const { success, data, message } = response.data
  if (success) {
    return data
  } else {
    Message.error(message)
    return Promise.reject(new Error(message))
  }
}, error => {
  if (error.response && error.response.status === 401) {
    store.dispatch('user/logout')
    router.push('/login')
  } else {
    Message.error(error.message)
  }

  return Promise.reject(error)
})

function CheckTimeStamp() {
  const oldTime = getStamp()
  const currentTime = +new Date()
  return (currentTime - oldTime) / 1000 > defaultStamp
}

export default service
